package com.imooc.distributedemo.resume.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

/**
 * leetcode215 数组中第K个最大元素
 */
public class Solution215 {

    public static void main(String[] args) {
        int[] nums = {19,3,2,1,5,6,4};
//        int r1 = findKthLargest1(nums, 2);
//        System.out.println(r1);

        int r2 = findKthLargest2(nums, 2);
        System.out.println(r2);
    }

    private static int findKthLargest2(int[] nums, int k) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        PriorityQueue<Integer> fullHeap = new PriorityQueue<>();
        for (int i = 0; i < nums.length; i++) {
            fullHeap.offer(nums[i]);
        }
        int a1 = fullHeap.poll();
        int a2 = fullHeap.poll();
        int a3 = fullHeap.poll();
        int a4 = fullHeap.poll();
        int a5 = fullHeap.poll();
        int a6 = fullHeap.poll();
        // fullHeap转移到列表
        List<Integer> list = new ArrayList<>(fullHeap);


        // 将前面k个元素初始化到小顶堆
        for (int i = 0; i < k; i++) {
            int tmp = nums[i];
            minHeap.offer(tmp);
        }
        // 剩余元素写入到小顶堆
        for (int i = k; i < nums.length; i++) {
            // 新元素如果比小顶堆最小元素大，那就加入进来
            if(nums[i]>minHeap.peek()){
                minHeap.poll();
                int tmp = nums[i];
                minHeap.offer(tmp);
            }
        }
        return minHeap.peek();
    }

    private static int findKthLargest1(int[] nums, int k) {
        Arrays.sort(nums);
        int data = nums[nums.length-k];
        return data;
    }

}
